package com.yuba.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuba.common.core.utils.MapstructUtils;
import com.yuba.common.core.utils.StringUtils;
import com.yuba.common.core.utils.ValidatorUtils;
import com.yuba.common.core.validate.AddGroup;
import com.yuba.common.mybatis.core.page.PageQuery;
import com.yuba.common.mybatis.core.page.TableDataInfo;
import com.yuba.front.domain.FishSiteComments;
import com.yuba.front.domain.FishSiteRatings;
import com.yuba.front.domain.bo.FishSiteCommentsBo;
import com.yuba.front.domain.vo.FishSiteCommentsVo;
import com.yuba.front.mapper.FishSiteCommentsMapper;
import com.yuba.front.mapper.FishSiteRatingsMapper;
import com.yuba.front.service.IFishSiteCommentsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 钓场评论Service业务层处理
 *
 * @author modakai
 * @date 2024-12-11
 */
@RequiredArgsConstructor
@Service
public class FishSiteCommentsServiceImpl implements IFishSiteCommentsService {

    private final FishSiteCommentsMapper baseMapper;
    private final FishSiteRatingsMapper fishSiteRatingsMapper;

    /**
     * 查询钓场评论
     *
     * @param commentsId 主键
     * @return 钓场评论
     */
    @Override
    public FishSiteCommentsVo queryById(Long commentsId){
        return baseMapper.selectVoById(commentsId);
    }

    /**
     * 分页查询钓场评论列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 钓场评论分页列表
     */
    @Override
    public TableDataInfo<FishSiteCommentsVo> queryPageList(FishSiteCommentsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FishSiteComments> lqw = buildQueryWrapper(bo);
        Page<FishSiteCommentsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<FishSiteCommentsVo> queryPageList(PageQuery pageQuery, Integer fishSiteId) {
        Page<FishSiteCommentsVo> result = baseMapper.selectVoPage(pageQuery.build(), fishSiteId);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的钓场评论列表
     *
     * @param bo 查询条件
     * @return 钓场评论列表
     */
    @Override
    public List<FishSiteCommentsVo> queryList(FishSiteCommentsBo bo) {
        LambdaQueryWrapper<FishSiteComments> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FishSiteComments> buildQueryWrapper(FishSiteCommentsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FishSiteComments> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getFishSiteId() != null, FishSiteComments::getFishSiteId, bo.getFishSiteId());
        lqw.eq(bo.getUserId() != null, FishSiteComments::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getComment()), FishSiteComments::getComment, bo.getComment());
        lqw.eq(bo.getRating() != null, FishSiteComments::getRating, bo.getRating());
        return lqw;
    }

    /**
     * 新增钓场评论
     *
     * @param bo 钓场评论
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(FishSiteCommentsBo bo) {
        FishSiteComments add = MapstructUtils.convert(bo, FishSiteComments.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCommentsId(add.getCommentsId());
        }
        return flag;
    }

    /**
     * 修改钓场评论
     *
     * @param bo 钓场评论
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(FishSiteCommentsBo bo) {
        FishSiteComments update = MapstructUtils.convert(bo, FishSiteComments.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FishSiteComments entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除钓场评论信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void pushFishSiteComment(FishSiteCommentsBo form, Long userId) {
        form.setUserId(userId);
        ValidatorUtils.validate(form, AddGroup.class);

        insertByBo(form);

        // 查询评分数据
        FishSiteRatings currentRating = fishSiteRatingsMapper.selectByFishSiteKey(form.getFishSiteId());
        if (currentRating == null) {
            // 第一条评论
            // 如果没有评分记录，则新增评分记录
            FishSiteRatings newRating = new FishSiteRatings();
            newRating.setFishSiteId(form.getFishSiteId());
            newRating.setAvgRating(BigDecimal.valueOf(form.getRating())); // 首次评分就是当前评分
            newRating.setRatingCount(1);
            fishSiteRatingsMapper.insert(newRating);
        } else {
            // 如果已有评分记录，则更新评分
            int newRatingCount = currentRating.getRatingCount() + 1; // 新的评分人数
            BigDecimal totalRating = currentRating.getAvgRating()
                .multiply(BigDecimal.valueOf(currentRating.getRatingCount())) // 当前总评分
                .add(BigDecimal.valueOf(form.getRating())); // 加上新的评分

            BigDecimal newAverageRating = totalRating.divide(BigDecimal.valueOf(newRatingCount), 2, RoundingMode.HALF_UP); // 计算新的平均评分

            currentRating.setAvgRating(newAverageRating);
            currentRating.setRatingCount(newRatingCount);
            fishSiteRatingsMapper.updateByPrimaryKey(currentRating); // 更新评分记录
        }
    }
}
